﻿#include "configoperate.h"

ConfigOperate::ConfigOperate()
{
    m_cfgFile = "user.ini";
    m_port = "55555";
    m_ipAddress = "127.0.0.1";

    initSystemInfo();
}

void ConfigOperate::initSystemInfo()
{
    QFileInfo info(m_cfgFile);
    if (!info.isFile()) /// 该文件不存在，创建文件-写入默认的配置
    {
        writeSystemInfo();
    }
    else {                  /// 该文件存在，创建文件-写入用户自定义的配置
        readSystemInfo();
    }
}

void ConfigOperate::readSystemInfo()
{
    readInit("TCPClientPort", "port", m_port);
    readInit("TCPServerIP", "ipAddress", m_ipAddress);
}

void ConfigOperate::writeSystemInfo()
{
    QSettings config(m_cfgFile, QSettings::IniFormat);

    config.beginGroup("TCPClientPort");
    config.setValue("port", m_port);
    config.endGroup();

    config.beginGroup("TCPServerIP");
    config.setValue("ipAddress", m_ipAddress);
    config.endGroup();
}

bool ConfigOperate::writeInit(QString group, QString key, QString value)
{
    if(group.isEmpty() || key.isEmpty())
    {
        return false;
    }else
    {
        //创建配置文件操作对象
        QSettings config(m_cfgFile, QSettings::IniFormat);

        //将信息写入配置文件
        config.beginGroup(group);
        config.setValue(key, value);
        config.endGroup();

        return true;
    }
}
bool ConfigOperate::readInit(QString group, QString key, QString &value)
{
    value.clear();
    if(group.isEmpty() || key.isEmpty())
    {
        return false;
    }
    else
    {
        //创建配置文件操作对象
        QSettings config(m_cfgFile, QSettings::IniFormat);

        //读取用户配置信息
        value = config.value(group + "/" + key).toString();

        return true;
    }
}

QString ConfigOperate::readPort()
{
    return m_port;
}
void ConfigOperate::writePort(QString value)
{
    m_port = value;
    writeInit("TCPClientPort", "port", m_port);
}

QString ConfigOperate::readIpAdress()
{
    return m_ipAddress;
}
void ConfigOperate::writeIpAdress(QString value)
{
    m_ipAddress = value;
    writeInit("TCPServerIP", "ipAddress", m_ipAddress);
}
